package com.xoa.plugin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xoa.dao.attend.AttendLeaveMapper;
import com.xoa.dao.document.DocumentModelMapper;
import com.xoa.dao.flowhook.FlowHookMapper;
import com.xoa.dao.workflow.FlowProcessMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.attend.AttendLeave;
import com.xoa.model.document.DocumentModel;
import com.xoa.model.document.DocumentModelWithBLOBs;
import com.xoa.model.workflow.FlowHookWithBLOBs;
import com.xoa.model.workflow.FlowProcess;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.service.work.impl.WorkServiceImpl;
import com.xoa.util.DateFormat;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.dataSource.ContextHolder;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.Key;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by gsb on 2017/7/29.
 */
@Service
public class DocumentTrigger implements TriggerSubject {
    @Resource
    private DocumentModelMapper documentModelMapper;
    @Resource
    private FlowProcessMapper flowProcessMapper;
    @Resource
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Autowired
    private FlowHookMapper flowHookMapper;



    @Override
    public void doRun(String company,Object... ags) {
        ContextHolder.setConsumerType(company);
        TriggerPlugIn tri = (TriggerPlugIn) ags[0];
        DocumentModelWithBLOBs documentModel = new DocumentModelWithBLOBs();
        documentModel.setId(Integer.parseInt(tri.getTabId()));
        if("1".equals(tri.getDistinguish())){
        documentModel.setFlowId(Integer.parseInt(tri.getFlowId()));
        documentModel.setFlowRunName(tri.getRunName());
       FlowProcess flowProcess= flowProcessMapper.findPrcessLine(Integer.parseInt(tri.getFlowId()),Integer.parseInt(tri.getPrcsId()));

     if(flowProcess!=null) {
         String prcs = flowProcess.getPrcsTo();
         if (!"".equals(prcs) && prcs != null) {
             prcs = prcs.substring(0, prcs.length() - 1);
             if ("0".equals(prcs)) {
                 documentModel.setFlowStatus("1");

             } else {
                 documentModel.setFlowStatus("0");
             }
         }
         documentModel.setFlowPrcs(tri.getCurrentPrcsId());
         Map<String,Object> maps=new HashMap<String,Object> ();
         maps.put("prcsId",tri.getPrcsId());
         maps.put("runId",tri.getRunId());

         List<FlowRunPrcs> flowRunPrcs= flowRunPrcsMapper.selectfrp(maps);
         Iterator<FlowRunPrcs> iterator=flowRunPrcs.iterator();
         StringBuffer stb=new StringBuffer();

         while (iterator.hasNext()){
             FlowRunPrcs flowRunPrcs1=iterator.next();
             if("1".equals(flowRunPrcs1.getOpFlag())) {
                 documentModel.setCurUserId(flowRunPrcs1.getUserId());
                DocumentModel documentModel1 = documentModelMapper.selectByPrimaryKey(Integer.parseInt(tri.getTabId()));
                 if (!StringUtils.checkNull(documentModel1.getAllUserId())) {
                     String[] str=documentModel1.getAllUserId().split(",");
                     for (int i=0;i<str.length;i++){
                         if(!str[i].equals(flowRunPrcs1.getUserId())){
                            documentModel.setAllUserId(documentModel1.getAllUserId()  + flowRunPrcs1.getUserId()+",");
                         }
                     }
                  } else {
                     documentModel.setAllUserId(flowRunPrcs1.getUserId()+",");
                 }
             }
         }


     }
             FlowHookWithBLOBs flowHookNew=new FlowHookWithBLOBs();
             flowHookNew.setHid(tri.getHookId());
             FlowHookWithBLOBs flowHook=  flowHookMapper.selectByhid(flowHookNew);
             Map<Object,Object> flowHookMaps=null;
             if(flowHook!=null){
                 flowHookMaps=queryTriggerField(tri.getModify(),tri.getReject(),flowHook.getMap(),flowHook.getDataDirection());
             }

             AttendLeave attendLeave=new AttendLeave();
             if(flowHookMaps!=null){
                 for (Map.Entry<Object,Object> entry : flowHookMaps.entrySet()) {
                     if(entry.getKey().equals("key_word")){
                         documentModel.setKeyWord(entry.getValue().toString());
                     }else if(entry.getKey().equals("unit")){
                         documentModel.setUnit(entry.getValue().toString());
                     }else if(entry.getKey().equals("title")){
                         documentModel.setTitle(entry.getValue().toString());
                     }else if(entry.getKey().equals("doc_no")){
                         documentModel.setDocNo(entry.getValue().toString());
                     }else if(entry.getKey().equals("urgency")) {
                         documentModel.setUrgency(entry.getValue().toString());
                     }else if(entry.getKey().equals("secrecy")){
                         documentModel.setSecrecy(entry.getValue().toString());
                     }else if(entry.getKey().equals("main_delivery")){
                         documentModel.setMainDelivery(entry.getValue().toString());
                     }else if(entry.getKey().equals("copy_delivery")){
                         documentModel.setCopyDelivery(entry.getValue().toString());
                     }else if(entry.getKey().equals("deadline")){
                         documentModel.setDeadline(Integer.valueOf(entry.getValue().toString()));
                     }else if(entry.getKey().equals("copies")){
                         documentModel.setCopies(Integer.valueOf(entry.getValue().toString()));
                     }else if(entry.getKey().equals("remark")){
                         documentModel.setRemark(entry.getValue().toString());
                     }else if(entry.getKey().equals("creater")){
                         documentModel.setCreater(entry.getValue().toString());
                     }else if(entry.getKey().equals("create_dept")){
                         documentModel.setCreateDept(entry.getValue().toString());
                     }else if(entry.getKey().equals("print_dept")){
                         documentModel.setPrintDept(entry.getValue().toString());
                     }else if(entry.getKey().equals("print_date")){
                         documentModel.setPrintDate(entry.getValue().toString());
                     }
                 }
             }


     }

        int a = documentModelMapper.updateByPrimaryKeySelective(documentModel);
        L.s("0=||=======>documentTrigger!");

    }
    public  Map<Object,Object> queryTriggerField(String modifydata,String fromdate,String maps,Integer num){

        //获取json串 进行判断
        //获取业务引擎接口的数据进行分开，组合map
        /**
         * 拿自己内置的数据去写的
         */

        String[] a=maps.split(",");
        Map<String,Object> map=new HashMap<String,Object>();
        for (int i=0;i<a.length;i++){
            String i1=a[i];
            String i2[]=i1.split("=>");
            String i3=i2[0];
            String i4=i2[1];
            map.put(i3,i4);
            //key           USER_ID
            //value         申请人

        }
        JSONArray json = new JSONArray();
        //String fromdateOne="["+fromdate+"]";
        Map<String, Object> from = json.parseObject(
                fromdate,new TypeReference<Map<String, Object>>(){} );


        List<Map<String, Object>> modify = json.parseObject(modifydata, List.class);
        //List<Map<String, Object>> from = json.parseObject(fromdate, List.class);
        Map<Object,Object> analysis=new HashMap<Object,Object>();
        Map<Object,Object> returnMap=new HashMap<Object,Object>();
        for (Map<String, Object> mapmodify : modify) {
            for (Map.Entry<String,Object> entry1 : from.entrySet()){
                if(mapmodify.get("key").equals(entry1.getValue())){
                    analysis.put(entry1.getKey(),mapmodify.get("value"));
                }

            }                        // 申请人   value   USER_ID
        }

          if("1".equals(num)){
        for (Map.Entry<Object,Object> entry : analysis.entrySet()) {//key 申请人 value  1
            for (Map.Entry<String,Object> entry1 : map.entrySet()) {
                if (entry.getKey().equals(entry1.getValue())) {
                    returnMap.put(entry1.getKey(),entry.getValue());

                }

            }

        }
        }else if("2".equals(num)){

          }
              for (Map.Entry<Object,Object> entry : analysis.entrySet()) {//key 申请人 value  1
                  for (Map.Entry<String,Object> entry1 : map.entrySet()) {
                      if (entry.getKey().equals(entry1.getKey())) {
                          returnMap.put(entry1.getValue(),entry.getValue());

                      }

                  }


          }



        return  returnMap;
    }
}
